package com.example.smsquiz;

import java.io.*;

public class TextDbProvider {

	String fileName;
	
	public TextDbProvider(String dbFileName){
		fileName = dbFileName;
	}
	
	public String getAnswerOnSimilarQuestion(String question) throws FileNotFoundException{
		File db = new File(fileName);
		if(!db.exists()){
			throw new FileNotFoundException();
		}
		BufferedReader reader = new BufferedReader(new FileReader(fileName));
		String line;
		try {
			while((line = reader.readLine()) != null){
				String[] cells = line.split("\t");
				if(question.contains(cells[0])){
					return cells[1];
				}
			}
            reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			AppLogger.WriteError(e);
		}
		return null;
	}

    public void AddQuestion(String question, String answer) throws IOException {
        File db = new File(fileName);
        if(!db.exists()){
            throw new FileNotFoundException();
        }
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
        StringBuilder builder = new StringBuilder();
        builder.append('\n');
        builder.append(question);
        builder.append('\t');
        builder.append(answer);
        writer.write(builder.toString());
        writer.close();
    }
}
